package net.monare.mifss;

import com.vaadin.annotations.PreserveOnRefresh;
import com.vaadin.annotations.Push;
import com.vaadin.annotations.Theme;
import com.vaadin.navigator.Navigator;
import com.vaadin.server.ErrorHandler;
import com.vaadin.server.VaadinRequest;
import com.vaadin.server.VaadinSession;
import com.vaadin.ui.Notification;
import com.vaadin.ui.UI;
import net.monare.mifss.admin.ui.AdminView;
import net.monare.mifss.admin.ui.LoginView;
import net.monare.mifss.admin.ui.LogoutView;
import org.apache.commons.lang.exception.ExceptionUtils;
import org.apache.log4j.Logger;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.ApplicationContext;
import org.springframework.context.annotation.Scope;
import org.springframework.security.authentication.AuthenticationManager;
import org.springframework.security.core.context.SecurityContext;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.stereotype.Component;

@Theme("runo")
@PreserveOnRefresh
@Push
@Component
@Scope("request")
public class MifssAdminMainUI extends UI implements ErrorHandler {

    private static final long serialVersionUID = -4116497957166577826L;

    Logger logger = Logger.getLogger(MifssAdminMainUI.class);

    @Autowired
    private transient ApplicationContext applicationContext;

    @Autowired
    private transient AuthenticationManager authenticationManager;

    private SecurityContext securityContext;

    @Autowired
    private MifssHolder mifssHolder;

    public SecurityContext getSecurityContext() {
        return this.securityContext;
    }

    public MifssHolder getMifssHolder() {
        return mifssHolder;
    }

    @Override
    protected void init(final VaadinRequest request) {

        // create view navigator
        Navigator navigator = new Navigator(this, this);
        navigator.addView("login", LoginView.class);
        navigator.addView("admin", AdminView.class);
        navigator.addView("logout", LogoutView.class);

        navigator.navigateTo("login");
        setNavigator(navigator);

        VaadinSession.getCurrent().setErrorHandler(this);

        securityContext = SecurityContextHolder.getContext();

    }

    @Override
    public void error(com.vaadin.server.ErrorEvent event) {

        logger.error(event.getThrowable(), event.getThrowable());

        String excString = ExceptionUtils.getStackTrace(event.getThrowable());

        Notification.show("ERROR", excString, Notification.Type.ERROR_MESSAGE);

        // Cleanup view. Now Vaadin ignores errors and always shows the view.  :-(
        // since beta10
        //  setContent(null);
        return;

    }

}
